package logic

import (
	"context"
	"fmt"
	"net/http"
	"path/filepath"
	"taobao/api/internal/svc"
	"taobao/api/internal/types"
	"taobao/api/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type QiniuyunLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewQiniuyunLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QiniuyunLogic {
	return &QiniuyunLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QiniuyunLogic) Qiniuyun(r *http.Request) (resp *types.RegMsgResponse, err error) {
	// todo: 图片上传

	file, image, err := r.FormFile("image")
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -1,
			Mag:  "文件获取失败",
			Data: nil,
		}, err
	}
	defer file.Close()

	etx := filepath.Ext(image.Filename)

	fmt.Print("文件后缀格式...............%", etx)

	if !(etx == ".png" || etx == ".jpg") {
		return &types.RegMsgResponse{
			Cre:  -1,
			Mag:  "文件格式错误",
			Data: nil,
		}, err
	}

	if image.Size > 1024*1024*2 {
		return &types.RegMsgResponse{
			Cre:  -2,
			Mag:  "文件内存过大",
			Data: nil,
		}, err
	}

	//图片地址
	imgUrl := pkg.Qiniuyun(file, image.Size)
	return &types.RegMsgResponse{
		Cre: 0,
		Mag: "上传成功",
		Data: map[string]interface{}{
			"imageUrl": imgUrl,
		},
	}, err
}
